﻿using System;
using System.Collections.Generic;
using MySql.Simple.Mapper.Attributes;
using MySql.Simple.Mapper.Structures;

namespace MySql.Simple.Mapper.Finders
{
    /// <summary>
    /// Finds the SQL indexes on a given type.
    /// </summary>
    public static class IndexFinder
    {
        /// <summary>
        /// Finds the SQL indexes on a given type.
        /// </summary>
        /// <param name="target">The target.</param>
        /// <returns></returns>
        public static IList<Index> Find(Type target)
        {
            var indices = new List<Index>();

            var properties = target.GetProperties();

            var sourceTableName = TableNameFinder.Find(target);

            foreach (var property in properties)
            {
                var attributes = property.GetCustomAttributes(typeof(IndexAttribute), true);

                var count = 0;

                foreach (var attribute in attributes)
                {
                    var indexAttribute = (IndexAttribute)attribute;

                    var index = new Index
                                    {
                                        Column = property.Name,
                                        Table = sourceTableName,
                                        IndexType = indexAttribute.IndexType,
                                        Length = indexAttribute.Length,
                                        Name = indexAttribute.Name,
                                        Id = count
                                    };

                    indices.Add(index);

                    count++;
                }
            }

            return indices;
        }
    }
}